/*********************************************************************\
*
*                  (c) lkc
*                  All Rights Reserved. lkc Confidential
*
\*********************************************************************/
/*********************************************************************\
*   Title                      :
*
*   Module Description         :
*
*   Author                     : lkc
*
*   Created                    : 2018-4-22
*
\*********************************************************************/

#include "DataStore.h"

//#include <sstream>
//#include <fstream>
//#include <QDebug>


//DataStore::DataStore(const std::string &saveName, const std::string &ranName, const std::string &header)
//{
//    std::string rootPrefix = "/tmp/data/";
////    std::string rootPrefix = "/home/root/data/";
//    std::string rootPostfix = ".csv";
//    m_saveRoot = rootPrefix+saveName+"_"+ranName+rootPostfix;
//    m_buffer[m_bufferIndex].push_back(header);
////    m_saveName = saveName;
//}

void DataStore::SetPar(const std::string& rootPre,const std::string& saveName, const std::string &ranName, const std::string& header)
{
//    std::string rootPrefix = "/tmp/data/";
//    std::string rootPrefix = "/home/root/data/";
    std::string rootPrefix= rootPre;
    std::string rootPostfix = ".csv";
    m_saveRoot = rootPrefix+saveName+"_"+ranName+rootPostfix;
    m_buffer[m_bufferIndex].push_back(header);
//    m_saveName = saveName;
}

void DataStore::StoreBuffer(const std::string &data)
{
    m_mtx.lock();
    m_buffer[m_bufferIndex].push_back(data);
    m_mtx.unlock();
}

void DataStore::StoreFlash()
{
//    auto start = std::chrono::system_clock::now();

    m_mtx.lock();
    int num = m_buffer[m_bufferIndex].size();
    if(num<=0)
    {
        m_mtx.unlock();
        return;
    }
    int storeIndex=m_bufferIndex;
    m_bufferIndex = (m_bufferIndex+1)%2;
    m_mtx.unlock();

    m_outfile.open(m_saveRoot, std::ostream::app);
    for(int i =0;i<num;i++)
    {
        m_outfile<<m_buffer[storeIndex][i];
    }
    m_buffer[storeIndex].clear();
    m_buffer[storeIndex].shrink_to_fit();
    m_outfile.close();

//    auto end = std::chrono::system_clock::now();
//    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
//    qDebug() <<"save"<<m_saveName.c_str()<<"cost time"<< static_cast<double>(duration.count())<< "us";
}






/********************************************************************\
 *
 * REVISION RECORDS
 *
\*********************************************************************/
/*********************************************************************/
/*
 *
 *
 *
\*********************************************************************/
/*------------------------------The End------------------------------*/
